<template>
  <div class="student-courses">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('course.studentCourses') }}</span>
      </div>
      <div v-if="loadingSelected" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="selectedCourses.length === 0" class="empty-data">
        <el-empty :description="$t('course.noSelectedCourses')" />
      </div>
      <el-table v-else :data="selectedCourses" style="width: 100%" border>
        <el-table-column prop="name" :label="$t('course.name')"></el-table-column>
        <el-table-column prop="info" :label="$t('course.description')"></el-table-column>
        <el-table-column prop="location" :label="$t('course.location')"></el-table-column>
        <el-table-column :label="$t('course.schedule')" width="180">
          <template slot-scope="scope">
            {{ scope.row.startTime }} - {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('course.duration')" width="200">
          <template slot-scope="scope">
            {{ scope.row.startDate }} {{ $t('common.to') }} {{ scope.row.endDate }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.operation')" width="120" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button 
              type="danger" 
              size="mini" 
              @click="unselectCourse(scope.row)"
              :loading="unselectLoading === scope.row.id">
              {{ $t('course.withdraw') }}
            </el-button>
          </template>
        </el-table-column>
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="120"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button 
                  type="danger" 
                  size="mini" 
                  @click="unselectCourse(scope.row)"
                  :loading="unselectLoading === scope.row.id">
                  {{ $t('course.withdraw') }}
                </el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="box-card mt-20">
      <div slot="header" class="clearfix">
        <span>{{ $t('course.available') }}</span>
      </div>
      <div v-if="loadingAvailable" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="availableCourses.length === 0" class="empty-data">
        <el-empty :description="$t('course.noAvailableCourses')" />
      </div>
      <el-table v-else :data="availableCourses" style="width: 100%" border>
        <el-table-column prop="name" :label="$t('course.name')"></el-table-column>
        <el-table-column prop="info" :label="$t('course.description')"></el-table-column>
        <el-table-column prop="location" :label="$t('course.location')"></el-table-column>
        <el-table-column :label="$t('course.schedule')" width="180">
          <template slot-scope="scope">
            {{ scope.row.startTime }} - {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('course.duration')" width="200">
          <template slot-scope="scope">
            {{ scope.row.startDate }} {{ $t('common.to') }} {{ scope.row.endDate }}
          </template>
        </el-table-column>
        <el-table-column prop="selectedNum" :label="$t('course.enrolled')" width="90" align="center"></el-table-column>
        <el-table-column prop="maxNum" :label="$t('course.capacity')" width="90" align="center"></el-table-column>
        <el-table-column :label="$t('common.operation')" width="120" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              size="mini" 
              @click="selectCourse(scope.row)" 
              :disabled="scope.row.selectedNum >= scope.row.maxNum"
              :loading="selectLoading === scope.row.id">
              {{ $t('course.select') }}
            </el-button>
          </template>
        </el-table-column>
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="120"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="selectCourse(scope.row)" 
                  :disabled="scope.row.selectedNum >= scope.row.maxNum"
                  :loading="selectLoading === scope.row.id">
                  {{ $t('course.select') }}
                </el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ElementUI from "element-ui";

export default {
  name: 'StudentCourses',
  data() {
    return {
      selectedCourses: [],
      availableCourses: [],
      loadingSelected: false,
      loadingAvailable: false,
      selectLoading: null,  // 记录正在选课的课程ID
      unselectLoading: null, // 记录正在退选的课程ID
      isMobile: false,
      screenWidth: document.body.clientWidth
    }
  },
  computed: {
    // 从 vuex 获取用户ID
    userInfo() {
      return JSON.parse(sessionStorage.getItem("userInfo")) || {};
    },
    userId() {
      return this.userInfo.userId;
    }
  },
  created() {
    this.getSelectedCourses();
    this.getAvailableCourses();
    this.checkScreenSize();
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    this.checkScreenSize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth;
      this.checkScreenSize();
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768;
    },
    // 获取已选课程
    getSelectedCourses() {
      if (!this.userId) {
        this.$message.error(this.$t('user.loginRequired'));
        return;
      }

      this.loadingSelected = true;
      this.$axios.get(`/course/student/${this.userId}`)
        .then(res => {
          this.loadingSelected = false;
          if (res.code === 200) {
            this.selectedCourses = res.data || [];
          } else {
            this.$message.error(res.data.msg || this.$t('course.getCoursesError'));
          }
        })
        .catch(error => {
          this.loadingSelected = false;
          console.error('获取已选课程失败:', error);
          this.$message.error(this.$t('common.operationFailedRetry'));
        });
    },

    // 获取可选课程
    getAvailableCourses() {
      if (!this.userId) {
        this.$message.error(this.$t('user.loginRequired'));
        return;
      }

      this.loadingAvailable = true;
      this.$axios.get(`/course/available/${this.userId}`)
        .then(res => {
          this.loadingAvailable = false;
          if (res.code === 200) {
            this.availableCourses = res.data || [];
          } else {
            this.$message.error(res.data.msg || this.$t('course.getCoursesError'));
          }
        })
        .catch(error => {
          this.loadingAvailable = false;
          console.error('获取可选课程失败:', error);
          this.$message.error(this.$t('common.operationFailedRetry'));
        });
    },

    // 选课
    selectCourse(course) {
      if (!this.userId) {
        this.$message.error(this.$t('user.loginRequired'));
        return;
      }

      const selectedCourseDTO = {
        userId: this.userId,
        courseId: course.id
      };

      this.selectLoading = course.id;
      this.$axios.post('/selectedCourse/select', selectedCourseDTO)
        .then(res => {
          this.selectLoading = null;
          if (res.code === 200) {
            this.$message.success(this.$t('common.operationSuccess'));
            this.getSelectedCourses();
            this.getAvailableCourses();
          } else {
            this.$message.error(res.data.msg || this.$t('common.operationFailed'));
          }
        })
        .catch(error => {
          this.selectLoading = null;
          console.error('选课失败:', error);
          this.$message.error(this.$t('common.operationFailedRetry'));
        });
    },

    // 退选
    unselectCourse(course) {
      if (!this.userId) {
        this.$message.error(this.$t('user.loginRequired'));
        return;
      }

      const selectedCourseDTO = {
        userId: this.userId,
        courseId: course.id
      };

      this.unselectLoading = course.id;
      this.$axios.post('/selectedCourse/unselect', selectedCourseDTO)
        .then(res => {
          this.unselectLoading = null;
          if (res.code === 200) {
            this.$message.success(this.$t('common.operationSuccess'));
            this.getSelectedCourses();
            this.getAvailableCourses();
          } else {
            this.$message.error(res.data.msg || this.$t('common.operationFailed'));
          }
        })
        .catch(error => {
          this.unselectLoading = null;
          console.error('退选失败:', error);
          this.$message.error(this.$t('common.operationFailedRetry'));
        });
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return this.$t('common.unknown');
      const hour = time.hour.toString().padStart(2, '0');
      const minute = time.minute.toString().padStart(2, '0');
      return `${hour}:${minute}`;
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return this.$t('common.unknown');
      return date;
    }
  }
}
</script>

<style lang="scss" scoped>
.student-courses {
  padding: 20px;
  
  .mt-20 {
    margin-top: 20px;
  }

  .loading-container, .empty-data {
    padding: 20px 0;
    display: flex;
    justify-content: center;
  }

  .el-table {
    margin-top: 10px;
  }
  
  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }

  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }

  // 响应式布局
  @media screen and (max-width: 768px) {
    padding: 10px;
    
    .el-card {
      margin-bottom: 10px;
    }
    
    .el-table {
      width: 100%;
      font-size: 12px;
    }
    
    .el-button {
      padding: 7px 10px;
      font-size: 12px;
    }
  }
}
</style> 